package com.example.h9iserver.domain;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author 4040
 * @Date 2025/7/29 10:33
 */
@Data
public class CustomUserDetails implements UserDetails {
    private final Long id;
    private final String username;
    private final String password;
    private final Set<String> roles;
    private final Set<String> authorities;
    private final boolean enabled;

    private final String name;

    private final String avatar;

    private final Integer gender;

    public CustomUserDetails(String username, String password, Set<String> roles, Set<String> authorities, boolean enabled, User user) {
        this.username = username;
        this.id = user.getId();
        this.password = password;
        this.roles = roles;
        this.authorities = authorities;
        this.enabled = enabled;
        this.name = user.getName();
        this.avatar = user.getAvatar();
        this.gender = user.getGender();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> simpleGrantedAuthorityList = new ArrayList<>();
        List<SimpleGrantedAuthority> roleAuthority = roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                .toList();
        List<SimpleGrantedAuthority> authorityAuthority = authorities.stream()
                .map(SimpleGrantedAuthority::new)
                .toList();
        simpleGrantedAuthorityList.addAll(roleAuthority);
        simpleGrantedAuthorityList.addAll(authorityAuthority);
        return simpleGrantedAuthorityList;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
